import {h, init} from 'snabbdom';
import style from 'snabbdom/modules/style'
import eventlisteners from 'snabbdom/modules/eventlisteners'
import 'bootstrap/dist/css/bootstrap.css';
import 'animate.css';
import dataModule from "./data";

let { data, leftData } = dataModule;

function renderData(data) {
  return data.map(item => generateChild(item));
}

function deleteRow(detailid) {
  data = data.filter(item => item.detailid !== detailid);

  reRender();
}

function generateChild(data) {
  return h('li.list-group-item.row.animate__animated.animate__backInLeft', {
    key: data.detailid,
    style: {
      remove: { 'animation-name': 'backOutRight' }
    },
    hook: {
      remove: (vnode) => {
        setTimeout(() => {
          vnode.elm.remove();
        }, 500);
      },
    }
  }, [
    h('span.col-sm-2', data.detailid),
    h('span.col-sm-3', data.name),
    h('span.col-sm-6', data.author),
    h('span.col-sm-1', [
      h('i.glyphicon.glyphicon-remove-sign', {
        on: { click: [deleteRow, data.detailid] }
      })
    ])
  ])
}

function sortBy(type) {
  data = data.sort(function (a, b) {
    if (a[type] < b[type]) {
      return -1;
    }  else if (a[type] > b[type]) {
      return 1;
    }

    return 0;
  });

  reRender();
}

function addData() {
  data.unshift(leftData.shift());

  reRender();
}

function getVnode(data) {
  return h('div.container', {}, [
    h('div.row.mb20', [
      h('div.pull-left', [
        h('span', 'Sort by:'),
        h('div.btn.btn-link', {
          on: {click: [sortBy, 'detailid']}
        }, 'DetailId'),
        h('div.btn.btn-link', {
          on: {click: [sortBy, 'name']}
        }, 'Name'),
        h('div.btn.btn-link', {
          on: {click: [sortBy, 'author']}
        }, 'Author')
      ]),
      h('button.btn.btn-primary.pull-right', {
        on: { click: addData }
      }, 'Add'),
    ]),
    h('ul.list-group', renderData(data)),
  ]);
}

let patch = init([
  style,
  eventlisteners,
]);

let vnode = getVnode(data);
let oldVnode = patch(document.querySelector('#app'), vnode);

function reRender() {
  vnode = getVnode(data);
  oldVnode = patch(oldVnode, vnode)
}

